<?php
/**
 * Created by PhpStorm.
 * User: mabao
 * 消息：系统消息和聊天消息和聊天
 */
namespace app\api\controller;
use think\Db;
use think\Config;
class News extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            echo json_encode(['status'=>301,'msg'=>"Token失效！请重新登录！"]);
            exit;
        }
    }
    /**
     * 获取聊天信息：从列表进或者从经纪人出聊天进或者从消息列表处进
     * 传参：user_id和user_id_other和page
     * 只要m_one_user_id==user_id，就说明是这条消息是我的，否则是对方的，头像都取这个，只是位置不同
     */
    public function getNewsRec()
    {
        extract(input());
        //m_one_user_id等于user_id就是我发的
        $data = Db::table('up_message')->alias('m')
            ->join('up_u_user u','m.m_one_user_id=u.user_id','LEFT')
            ->where (function ($query) use ($user_id,$user_id_other){
                $query->where('m_one_user_id',$user_id)->where('m_reply_user_id',$user_id_other);
            })
            ->whereOr(function ($query) use ($user_id,$user_id_other){
                $query->where('m_reply_user_id',$user_id)->where('m_one_user_id',$user_id_other);
            })
            ->order('m_time DESC')
            ->field('user_image,m_content,m_time,m_one_user_id,m_reply_user_id')
            ->page($page,20)
            ->select();
//        ---------------------所有和此人的消息改状态start---------------------
        Db::table('up_message')
            ->where('m_reply_user_id',$user_id)
            ->where('m_one_user_id',$user_id_other)
            ->where('m_read','notlike',"%,$user_id,%")
            ->update(['m_read'=>",$user_id,$user_id_other,"]);
//        ---------------------所有和此人的消息改状态 end----------------------
        $data = array_reverse($data);
        $who = Db::table('up_u_user')->where('user_id',$user_id_other)->value('user_username');
        return json(['status'=>200,'msg'=>$data,'who'=>$who]);
    }
    /**
     * 发聊天信息
     * 传参：user_id和user_id_other和$m_content
     * 只要m_one_user_id==user_id，就说明是这条消息是我的，否则是对方的，头像都取这个，只是位置不同
     */
    public function startChats()
    {
        extract(input());
        $have = Db::table('up_message')
            ->where (function ($query) use ($user_id,$user_id_other){
                $query->where('m_one_user_id',$user_id)->where('m_reply_user_id',$user_id_other);
            })
            ->whereOr(function ($query) use ($user_id,$user_id_other){
                $query->where('m_reply_user_id',$user_id)->where('m_one_user_id',$user_id_other);
            })
            ->find();
        $data = array();
        $data['m_one_user_id'] = $user_id;
        $data['m_reply_user_id'] = $user_id_other;
        $data['m_content'] = $m_content;
        $data['m_time'] = date('Y-m-d H:i:s');
        $data['m_start'] = $user_id;
        $data['m_end'] = $user_id_other;
        $data['m_read'] = ',' . $user_id . ',';
        if($have){
            $data['m_start'] = $have['m_start'];
            $data['m_end'] = $have['m_end'];
        }
        $res = Db::table('up_message')->insert($data);
        if($res){
            return json(['status'=>200,'msg'=>'发送成功']);
        }else{
            return json(['status'=>0,'msg'=>'发送失败']);
        }
    }
    /**
     * 获得聊天列表
     * 传参：user_id和user_id_other和page
     * 如果m_one_user_id==user_id，取reply_name...，否则昵称取one_name...
     * 给了个user_id_other的字段，对方的id，获取聊天记录时，对方的就传这个
     */
    public function chatList()
    {
        extract(input());
        $data = Db::table('up_message')->alias('m')
            ->join('up_u_user u','m.m_one_user_id=u.user_id','LEFT')
            ->join('up_u_user u2','m.m_reply_user_id=u2.user_id','LEFT')
            ->where('m_one_user_id',$user_id)
            ->whereOr('m_reply_user_id',$user_id)
            ->order('m_time DESC')
            ->group('m_start,m_end')
            ->field('u.user_image one_image,u2.user_image reply_image,u.user_username one_name,u2.user_username reply_name,max(m_time) m_time,max(m_id) m_id,m_one_user_id,m_reply_user_id')
            ->page($page,15)
            ->select();
        if($data){
            foreach ($data as $k=>$v){
                $con = Db::table('up_message')->where('m_id',$v['m_id'])
                    ->field('m_one_user_id,m_reply_user_id,m_content')->find();
                $data[$k]['m_content'] = $con['m_content'];
                $data[$k]['user_id_other'] = $con['m_one_user_id'];
                if($con['m_one_user_id'] == $user_id){
                    $data[$k]['user_id_other'] = $con['m_reply_user_id'];
                }
                //---------------------------计算未读数量start-------------------------------------
                $noRead = Db::table('up_message')
                    ->where('m_reply_user_id',$user_id)
                    ->where('m_one_user_id',$data[$k]['user_id_other'])
                    ->where('m_read','notlike',"%,$user_id,%")
                    ->count();
                $data[$k]['no_read_num'] = $noRead;
                //---------------------------计算未读数量 end -------------------------------------
            }
        }
        $system = 1;//没有未读的
       $have = Db::table('up_notice')
            ->where('n_read','notlike',"%,$user_id,%")
            ->find();
       if($have){
           $system = 2;
       }
        return json(['status'=>200,'msg'=>$data,'system'=>$system]);
    }

    /**
     * 获取总的未读的消息
     */
    public function getAllMessNum()
    {
        extract(input());
        $noRead = Db::table('up_message')
            ->where('m_reply_user_id',$user_id)
            ->where('m_read','notlike',"%,$user_id,%")
            ->count();
        $noReadNotice = Db::table('up_notice')
            ->where('n_read','notlike',"%,$user_id,%")
            ->count();
        return json(['status'=>200,'msg'=>$noRead,'noReadNotice'=>$noReadNotice]);
    }
    /**
     * 获得系统消息列表
     *
     */
    public function getSystemNews()
    {
        extract(input());
        $data = Db::table('up_notice')
            ->order('n_time DESC')
            ->page($page,15)
            ->select();
        //列表处就得把文字类型的先改为已读
        $no = Db::table('up_notice')
            ->where('n_type',1)
            ->where('n_read','notlike',"%,$user_id,%")
            ->field('n_id,n_read')
            ->select();
        if($no){
            foreach ($no as $k=>$v){
                $str = $v['n_read'].$user_id.',';
                Db::table('up_notice')
                    ->where('n_id',$v['n_id'])
                    ->update(['n_read'=>$str]);
            }
        }
        if($data){
            foreach ($data as $k2=>$v2){
                if(strpos($v2['n_read'],",$user_id,") !== false){//已读，不显示红点
                    $data[$k2]['read'] = 1;
                }else{
                    $data[$k2]['read'] = 2;//未读，显示红点
                }
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 获得系统消息详情
     *
     */
    public function getSystemNewsInfo()
    {
        extract(input());
        $data = Db::table('up_notice')
            ->where('n_id',$n_id)
            ->find();
        if(strpos($data['n_read'],",$user_id,") !== false){//包含就算了
            return json(['status'=>200,'msg'=>$data]);
        }else{
            $str = $data['n_read'].$user_id.',';
            Db::table('up_notice')
                ->where('n_id',$data['n_id'])
                ->update(['n_read'=>$str]);
            return json(['status'=>200,'msg'=>$data]);
        }

    }



}